import Cookies from "js-cookie";
import Vue from "vue";
import VueRouter from "vue-router";
import routes from './routes.js'

Vue.use(VueRouter)

const router =  new VueRouter({
  routes:routes
})
//重写push和replace方法
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function(location,resolve,reject){
  if(resolve&&reject){
    originPush.call(this,location,resolve,reject)
  }else{
    originPush.call(this,location,()=>{},()=>{})
  }
}
VueRouter.prototype.replace = function(location,resolve,reject){
  if(resolve&&reject){
    originReplace.call(this,location,resolve,reject)
  }else{
    originReplace.call(this,location,()=>{},()=>{})
  }
}

// 全局前置路由守卫
router.beforeEach((to,from,next)=>{
  const token = Cookies.get('token')
  // 已登录
  if(token){
    if(to.path == '/login'){
      next(false)
    }else{
      next()
    }
  }else{
    //未登录：不允许跳转到其他页面
    if(to.path!='/login'){
      next('login')
    }else{
      next()
    }

  }
})

export default router